﻿using Autofac;
using System.Reflection;

namespace ZGLXM.Writh.Api
{
    public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // 加载程序集
            var applicationAssembly = Assembly.Load("ZGLXM.Infra");

            ////遍历程序集中的所有类型
            //foreach (var item in applicationAssembly.GetTypes())
            //{
            //    Console.WriteLine("Type" + item.Name);
            //}

            // 获取所有具体实现类和其接口
            var types = applicationAssembly.GetTypes()
                .Where(t => t is { IsClass: true, IsAbstract: false, IsGenericType: false }) // 只选择具体类且不是泛型
                .SelectMany(t => t.GetInterfaces(), (t, i) => new { Implementation = t, Interface = i })
                .Where(x => !x.Interface.IsGenericType || x.Interface.IsGenericTypeDefinition == false) // 过滤掉开放泛型接口
                .Where(x=>!x.Interface.Name.Contains("Base"))//过滤掉基类
                .Where(x=>x.Interface.Name.EndsWith("Repository"))
                .ToList();

            // 注册所有接口和实现
            foreach (var type in types)
            {
                builder.RegisterType(type.Implementation).As(type.Interface);
            }
        }
    }
}
